package com.wf.course.web.controller.course;

import com.google.gson.Gson;
import com.utils.page.PageBean;
import com.wf.course.model.ad.VipCard;
import com.wf.course.model.comm.GroupBuying;
import com.wf.course.model.course.CourseChapter;
import com.wf.course.model.course.CourseInfo;
import com.wf.course.model.course.CourseShare;
import com.wf.course.service.ICourseChapterService;
import com.wf.course.service.ICourseInfoService;
import com.wf.course.service.ICourseShareService;
import com.wf.course.service.IVipCardService;
import com.wf.course.web.Constants;
import com.wf.course.web.OSSUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("course/share")
public class CourseShareController {

    private static Logger logger = LoggerFactory.getLogger(CourseShareController.class);

    @Autowired
    private ICourseShareService courseShareService;
    @Autowired
    private ICourseInfoService courseInfoService;
    @Autowired
    private IVipCardService vipCardService;
    @Autowired
    private ICourseChapterService courseChapterService;

    @RequestMapping("list")
    public ModelAndView list(ModelAndView mav, Integer pageNo, Integer pageSize, CourseShare courseShare) {
        try {
            PageBean<CourseShare> pageBean = new PageBean<>(pageNo, pageSize);
            pageBean.setObj(courseShare);
            pageBean.setUrl("course/share/list");
            courseShareService.list(pageBean);
            StringBuilder builder = new StringBuilder();
            for (Field f : courseShare.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (null != f.get(courseShare) && StringUtils.isNotBlank(f.get(courseShare).toString())) {
                    builder.append("&" + f.getName() + "=" + f.get(courseShare));
                }
            }
            pageBean.setParams(builder.toString());
            mav.addObject("page", pageBean);
            mav.setViewName("course/share/list");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return mav;
    }

    @RequestMapping("toEdit/{id}")
    public String toEdit(@PathVariable("id") Integer id, Model model) {
        try {
            model.addAttribute("courses", courseInfoService.queryCourses());
            model.addAttribute("cards", vipCardService.queryVipCards());
            model.addAttribute("chapters", new Gson().toJson(courseChapterService.queryCourseChapters().stream()
                    .collect(Collectors.groupingBy(CourseChapter::getCourseId))));
            if (id > 0) {
                model.addAttribute("courseShare", courseShareService.queryCourseShareById(id));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return "course/share/edit";
    }

    @RequestMapping("delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        courseShareService.deleteCourseShareById(id);
        return "redirect:/course/share/list";
    }

    @RequestMapping("edit")
    public String edit(CourseShare courseShare) {
        try {
            if (courseShare.getFile() != null && courseShare.getFile().getSize() != 0) {
                if (courseShare.getId() != null) {
                    CourseShare cs = courseShareService.queryCourseShareById(courseShare.getId());
                    try {
                        if (StringUtils.isNotBlank(cs.getImages())) {
                            // 删除原来图片
                            OSSUtil.delete(cs.getImages(), Constants.IGM_BUCKET);
                        }
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
                // 重新上传
                String imgPath = "";
                try {
                    imgPath = OSSUtil.addFile(courseShare.getFile(), "course_share", Constants.IGM_BUCKET);
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
                courseShare.setImages(imgPath);
            }
            switch (courseShare.getType()) {
                case 1:
                    courseShare.setForeignId(courseShare.getCourseIds());
                    break;
                case 2:
                    courseShare.setForeignId(courseShare.getChapterIds());
                    break;
                case 3:
                    courseShare.setForeignId(courseShare.getCardIds());
                    break;
            }
            if (null != courseShare.getId()) {
                courseShareService.update(courseShare);
            } else {
                courseShareService.insert(courseShare);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "redirect:/course/share/list";
    }
}
